package com.simple.application;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;

/**
 * 调用SpringApplication.run()启动tomcat
 */
public class SpringApplication {
    /**
     * 启动Tomcat
     */
    public static void run() {
        try {
            Tomcat tomcat = new Tomcat();
            File baseDir = createTempDir();
            tomcat.setBaseDir(baseDir.getAbsolutePath());
            tomcat.getHost().setAutoDeploy(false);
            tomcat.addWebapp("/",baseDir.getAbsolutePath());
            tomcat.setPort(8080);
            tomcat.start();
            tomcat.getServer().await();
        } catch (IOException e) {
            System.out.println(e);
        } catch (LifecycleException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建临时文件夹
     * @return
     * @throws IOException
     */
    private static File createTempDir() throws IOException {
        File tempDir = File.createTempFile("tomcat", ".suffix");
        tempDir.delete();
        tempDir.mkdir();
        tempDir.deleteOnExit();
        return tempDir;
    }
}
